<template>
	<view class="container">
		<!-- 订阅消息授权引导 -->
		<view v-if="showSubscribeGuide" class="subscribe-guide">
			<view class="guide-content">
				<text class="guide-title">开启消息通知</text>
				<text class="guide-desc">及时获取工单状态更新提醒，不错过任何重要信息</text>
				<view class="guide-btns">
					<button class="cancel-btn" @click="showSubscribeGuide = false">暂不开启</button>
					<button class="confirm-btn" @click="handleSubscribeAuth">立即开启</button>
				</view>
			</view>
		</view>

		<view class="tab-bar">
			<view v-for="(item, index) in tabList" :key="index" class="tab-item" :class="{ active: current === index }"
				@click="onTabClick(index)">
				{{ item.name }}
			</view>
		</view>

		<!-- 当选中“进行中”时显示状态选项（已删除待审批） -->
		<view v-if="current === 0" class="status-filter">
			<view style="margin:10px 15px;font-size:16px;">状态</view>
			<view class="status">
				<view v-for="(status, statusIndex) in statusList" :key="statusIndex" class="status-item"
					:class="{ active: activeStatus === statusIndex }" @click="changeStatus(statusIndex)"
					hover-class="none">
					{{ status }}
				</view>
			</view>
		</view>

		<!-- 搜索框 -->
		<view class="search-bar">
			<input type="text" placeholder="输入位置、对象、描述" v-model="searchKeyword" @input="onSearch" />
		</view>

		<!-- 消息订阅设置入口 -->
		<view class="subscribe-setting" @click="toggleSubscribeSetting">
			<text v-if="subscribeStatus === 'accept'">消息订阅已开启</text>
			<text v-else>消息订阅已关闭</text>
			<text class="setting-btn" :style="{color: subscribeStatus === 'accept' ? '#e53e3e' : '#2BA245'}">
				{{ subscribeStatus === 'accept' ? '点击关闭' : '点击开启' }}
			</text>
		</view>

		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 加载中状态 -->
			<view v-if="isLoading" class="loading">
				<uni-loading-icon size="24" color="#2BA245"></uni-loading-icon>
				<text>加载中...</text>
			</view>

			<!-- 空状态 -->
			<view v-else-if="filteredOrders.length === 0" class="empty-state">
				<image src="/static/wrench.png"></image>
				<text>亲，您暂未报单，请去创建吧！</text>
				<button @click="createReport">报单</button>
			</view>

			<!-- 工单列表 -->
			<view v-else class="order-list">
				<view class="order-item" v-for="order in filteredOrders" :key="order.id"
					@click="goToOrderDetail(order)">
					<!-- 顶部：工单编号 + 状态标签 -->
					<view class="order-header flex justify-between items-center mb-3">
						<text class="order-number text-xs text-gray-500">工单编号：{{ order.orderNumber }}</text>
						<text
							:class="'order-status px-2 py-1 rounded-md text-xs font-medium ' + getStatusClass(order.status)">{{ order.statusText }}</text>
					</view>

					<!-- 标题行 -->
					<view class="order-title font-bold text-lg mb-2">{{ order.title }}</view>

					<!-- 基本信息行 -->
					<view class="order-info flex flex-wrap gap-x-10 gap-y-2 text-sm text-gray-600 mb-3">
						<view class="flex items-center">
							<uni-icon type="map-pin" size="14" color="#999" class="mr-1" />
							<text>{{ order.unit || '无单位信息' }}</text>
						</view>
						<view class="flex items-center">
							<uni-icon type="navigation" size="14" color="#999" class="mr-1" />
							<text>{{ order.location }}</text>
						</view>
					</view>

					<!-- 描述信息 -->
					<view class="order-desc text-sm text-gray-600 mb-3" v-if="order.description">
						<text class="text-gray-500">描述：</text>
						<text>{{ order.description }}</text>
					</view>

					<!-- 底部：时间 + 来源 + 联系人 -->
					<view class="order-meta flex justify-between items-center text-xs text-gray-500">
						<text class="flex items-center">
							<uni-icon type="time" size="14" color="#999" class="mr-1" />
							{{ formatTime(order.reportTime) }}
						</text>
						<text>{{ order.source }}</text>
						<text class="flex items-center">
							<uni-icon type="phone" size="14" color="#999" class="mr-1" />
							{{ order.reporterName }}({{ order.reporterPhone }})
						</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 关闭订阅确认弹窗 -->
		<view v-if="showCloseConfirm" class="confirm-modal">
			<view class="modal-content">
				<text class="modal-title">关闭消息订阅？</text>
				<text class="modal-desc">关闭后将无法接收工单状态更新提醒，是否确认？</text>
				<view class="modal-btns">
					<button class="modal-cancel" @click="showCloseConfirm = false">取消</button>
					<button class="modal-confirm" @click="confirmCloseSubscribe">确认关闭</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getBaoDanList,
		formatTime
	} from "./baoxiu.js"


	export default {
		data() {
			return {
				// 1. 标签页删除“待评价”，保留3个标签
				tabList: [{
						name: '进行中'
					},
					{
						name: '已驳回'
					},
					{
						name: '已终止'
					},
					{
						name: '已完成'
					}
				],
				current: 0, // 默认选中“进行中”
				// 2. 状态筛选列表删除“待审批”，保留3项
				statusList: ['全部', '待处理', '处理中', '待验收'], // 新增“已驳回”
				activeStatus: 0,
				searchKeyword: '',
				isLoading: false,
				orders: [],
				needRefresh: false, // 新增：刷新标识
				showSubscribeGuide: false,
				subscribeStatus: null,
				showCloseConfirm: false
			};
		},
		computed: {
			filteredOrders() {
				const statusFilter = this.tabList[this.current].name;
				const result = this.orders.filter(order => {
					const statusMatch = this.matchStatus(order, statusFilter);
					const keywordMatch = this.searchKeyword === '' ||
						(order.title && order.title.includes(this.searchKeyword)) ||
						(order.description && order.description.includes(this.searchKeyword)) ||
						(order.location && order.location.includes(this.searchKeyword));
					return statusMatch && keywordMatch;
				});
				return result;
			}
		},
		onLoad() {
			try {
				this.initSubscribeStatus();
				this.fetchOrders();
			} catch (error) {
				console.error('页面加载失败', error);
			}
		},
		onShow() {
		    // 关键：如果评价页面返回时标记了需要刷新，则重新获取数据
		    if (this.needRefresh) {
		      this.fetchOrders(); // 重新调用获取工单列表的方法
		      this.needRefresh = false; // 重置标识
		    }
		  },
		methods: {
			formatTime(timestamp) {
				return formatTime(timestamp);
			},
			initSubscribeStatus() {
				const subscribeInfo = uni.getStorageSync('subscribeStatus');
				this.subscribeStatus = subscribeInfo || null;
				this.showSubscribeGuide = !subscribeInfo;
			},

			toggleSubscribeSetting() {
				if (this.subscribeStatus === 'accept') {
					this.showCloseConfirm = true;
				} else {
					this.showSubscribeGuide = true;
				}
			},

			handleSubscribeAuth() {
				this.showSubscribeGuide = false;
				uni.requestSubscribeMessage({
					tmplIds: ['N1BgeMNFfZCjVFhUYL0mce1fpOxyitrp4Al-i8MX2r8'],
					success: (res) => {
						const templateId = 'N1BgeMNFfZCjVFhUYL0mce1fpOxyitrp4Al-i8MX2r8';
						if (res[templateId] === 'accept') {
							this.subscribeStatus = 'accept';
							uni.showToast({
								title: '消息通知已开启',
								icon: 'success'
							});
						} else if (res[templateId] === 'reject') {
							this.subscribeStatus = 'reject';
							uni.showToast({
								title: '已拒绝消息通知，可前往设置重新开启',
								icon: 'none'
							});
						}
						uni.setStorageSync('subscribeStatus', this.subscribeStatus);
					},
					fail: (err) => {
						console.error('订阅授权失败', err);
						if (err.errCode === 20004) {
							this.subscribeStatus = 'reject';
							uni.setStorageSync('subscribeStatus', 'reject');
							uni.showToast({
								title: '已拒绝消息通知，可前往设置重新开启',
								icon: 'none'
							});
						} else {
							uni.showToast({
								title: '授权失败，请稍后重试',
								icon: 'none'
							});
						}
					}
				});
			},

			confirmCloseSubscribe() {
				this.subscribeStatus = 'reject';
				uni.setStorageSync('subscribeStatus', 'reject');
				this.showCloseConfirm = false;
				uni.showToast({
					title: '已关闭消息订阅功能',
					icon: 'success'
				});
			},

			onTabClick(index) {
				this.current = index;
				if (index !== 0) this.activeStatus = 0;
			},

			changeStatus(index) {
				this.activeStatus = index;
			},

			createReport() {
				uni.navigateTo({
					url: '/life/repair/repair'
				});
			},

			goToOrderDetail(order) {
				const orderWithFlag = {
					...order,
					isRepairPage: true
				};
				const orderStr = encodeURIComponent(JSON.stringify(orderWithFlag));
				uni.navigateTo({
					url: `/life/repairDetail/repairDetail?order=${orderStr}`
				});
			},

			matchStatus(order, statusFilter) {
				// 3. 状态映射删除待评价和待审批相关配置
				const statusMap = {
					'进行中': ['0', '1', '2'], // 待处理、处理中、待验收
					'已驳回': ['4'],
					'已终止': ['5'],
					'已完成': ['3'] // 新增“已驳回”状态码映射
				};

				// 先过滤大标签
				if (!statusMap[statusFilter]?.includes(order.status)) {
					return false;
				}

				// 处理“进行中”的子状态筛选（删除待审批映射）
				if (statusFilter === '进行中') {
					const indexToStatus = [
						['0', '1', '2'], // 0:全部（不含已驳回）
						['0'], // 1:待处理
						['1'], // 2:处理中
						['2'] // 3:待验收
					];
					return indexToStatus[this.activeStatus].includes(order.status);
				}

				return true;
			},

			getStatusClass(status) {
				// 4. 状态样式删除待评价和待审批相关配置
				const classMap = {
					'0': 'status-pending',
					'1': 'status-processing',
					'2': 'status-pending-review',
					'3': 'status-completed', // 新增已驳回的样式类
					'4': 'status-rejected',
					'5': 'status-terminated'
				};
				return classMap[status] || '';
			},

			onSearch() {},

			async fetchOrders() {
				this.isLoading = true;
				try {
					const res = await getBaoDanList();
					if (res.success === true) {
						const rawOrders = Array.isArray(res.data.workorder) ? res.data.workorder : [];

						const orderList = rawOrders.map(item => {
							// 5. 状态文本映射删除待评价和待审批
							const statusTextMap = {
								'0': '待处理',
								'1': '处理中',
								'2': '待验收',
								'3': '已完成', // 关键映射
								'4': '已驳回',
								'5': '已终止'
							};

							// 处理image字段
							const images = Array.isArray(item.image) ?
								item.image.filter(img => typeof img === 'string' && img.trim()) : [];

							// 处理successImage字段
							const successImage = Array.isArray(item.successImage) ?
								item.successImage.filter(img => typeof img === 'string' && img.trim()) : [];

							// 提取处理人信息
							const processorInfo = typeof item.processor === 'object' && item.processor !==
								null ?
								item.processor : {};

							// 计算处理时间
							const processStartTime = item.processStartTime ? new Date(item.processStartTime) :
								null;
							const processEndTime = item.processEndTime ? new Date(item.processEndTime) : null;
							let timeConsumed = null;

							if (processStartTime && processEndTime) {
								const diffMs = processEndTime - processStartTime;
								const hours = Math.floor(diffMs / 3600000);
								const minutes = Math.floor((diffMs % 3600000) / 60000);
								timeConsumed = hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`;
							}
							return {
								id: item.id,
								orderNumber: item.orderNumber,
								title: item.repairObject || `工单#${item.orderNumber}`,
								unit: item.unit,
								location: item.location || item.unit,
								description: item.description || '无描述',
								reportTime: item.reportTime || item.createdAt,
								reporterName: item.reporterName,
								reporterPhone: item.reporterPhone,
								source: item.source || '未知来源',
								processor: item.processor,
								status: item.status,
								evaluateDetails: item.evaluateDetails,
								evaluatetext: item.evaluatetext,
								starLevel: item.starLevel || 0,
								statusText: statusTextMap[item.status] || `状态码: ${item.status}`,
								successtext: item.successtext,
								images: images,
								successImage: successImage,
								processorId: item.maintainerId,
								processorName: processorInfo.name || '未分配',
								processorPhone: processorInfo.phone || '',
								timeConsumed: timeConsumed || item.timeConsumed,
								createdAt: item.createdAt,
								updatedAt: item.updatedAt,
								enterpriseCode: item.EnterpriseCode || "GK001"
							};
						});
						this.orders = orderList;
					} else {
						console.warn('fetchOrders：接口请求失败', res.msg || '未知错误');
					}
				} catch (error) {
					console.error('fetchOrders：请求异常', error);
				} finally {
					this.isLoading = false;
				}
			},
			showOrderUpdateToast(order) {
				uni.showToast({
					title: `工单${order.id}状态更新为${order.statusText}`,
					icon: 'none',
					duration: 3000
				});
			}
		}
	};
</script>

<style scoped>
	/* 基础组件样式保持不变 */
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.tab-bar {
		display: flex;
		border-bottom: 1px solid #eee;
		background-color: white;
	}

	.tab-item {
		flex: 1;
		padding: 10px;
		font-size: 16px;
		color: #999;
		text-align: center;
	}

	.tab-item.active {
		color: #2BA245;
		border-bottom: 2px solid #2BA245;
		font-weight: bold;
	}

	/* 订阅设置样式 */
	.subscribe-setting {
		padding: 10px 15px;
		margin: 10px 0;
		background-color: #f0f9f0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 14px;
	}

	.setting-btn {
		font-weight: bold;
	}

	/* 模态框和引导样式 */
	.subscribe-guide,
	.confirm-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.subscribe-guide {
		z-index: 999;
	}

	.confirm-modal {
		z-index: 1000;
	}

	.guide-content,
	.modal-content {
		width: 80%;
		padding: 30rpx;
		background-color: white;
		border-radius: 16rpx;
		text-align: center;
	}

	.guide-title,
	.modal-title {
		display: block;
		font-weight: bold;
		color: #333;
		margin-bottom: 15rpx;
	}

	.guide-title {
		font-size: 20px;
	}

	.modal-title {
		font-size: 18px;
		margin-bottom: 15px;
	}

	.guide-desc,
	.modal-desc {
		display: block;
		font-size: 14px;
		color: #666;
		line-height: 1.5;
		margin-bottom: 30rpx;
	}

	.modal-desc {
		margin-bottom: 25px;
	}

	.guide-btns,
	.modal-btns {
		display: flex;
		justify-content: space-around;
	}

	/* 状态筛选样式 */
	.status-filter {
		margin-bottom: 10px;
		background-color: white;
	}

	.status-filter>view:first-child {
		margin: 10px 15px;
		font-size: 16px;
	}

	.status {
		display: flex;
		justify-content: space-around;
		padding: 10px 0;
	}

	.status-item {
		padding: 5px 15px;
		font-size: 14px;
		color: #666;
		background-color: #f5f5f5;
		border-radius: 20px;
	}

	.status-item.active {
		color: white;
		background-color: #2BA245;
		font-weight: bold;
	}

	/* 搜索栏样式 */
	.search-bar {
		padding: 10px;
		background-color: white;
		box-sizing: border-box;
	}

	.search-bar input {
		width: 100%;
		height: 40px;
		line-height: 40px;
		padding: 0 15px;
		font-size: 14px;
		color: #333;
		background-color: #f5f5f5;
		border: none;
		border-radius: 20px;
		box-sizing: border-box;
	}

	/* 内容区域样式 */
	.main-content {
		padding: 10px;
	}

	.loading {
		padding: 20px;
		text-align: center;
	}

	.empty-state {
		min-height: 300px;
		padding: 20px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.empty-state image {
		width: 100px;
		height: 100px;
		margin-bottom: 15px;
	}

	.empty-state text {
		margin-bottom: 20px;
		color: #999;
	}

	.empty-state button {
		width: 180px;
		height: 40px;
		line-height: 40px;
		font-size: 16px;
		color: white;
		background-color: #2BA245;
		border-radius: 20px;
	}

	/* 工单列表样式 */
	.order-list {
		background-color: white;
		border-radius: 10px;
		overflow: hidden;
	}

	.order-item {
		padding: 15px;
		border-bottom: 1px solid #eee;
	}

	.order-item:active {
		background-color: #f9f9f9;
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10px;
	}

	.order-number {
		font-size: 12px;
		color: #666;
	}

	.order-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}

	.order-status {
		padding: 2px 8px;
		font-size: 12px;
		border-radius: 4px;
		color: white;
	}

	.status-pending {
		background-color: #FF9800;
	}

	.status-processing {
		background-color: #2196F3;
	}

	.status-pending-review {
		background-color: #FFC107;
	}

	.status-completed {
		background-color: #2BA245;
	}

	.status-terminated {
		background-color: #F44336;
	}

	.order-info {
		display: flex;
		flex-wrap: wrap;
		gap: 15px 20px;
		font-size: 14px;
		color: #666;
	}

	.order-desc {
		font-size: 14px;
		line-height: 1.5;
		padding-left: 2px;
		margin-bottom: 10px;
	}

	.order-meta {
		padding-top: 5px;
		border-top: 1px dashed #f0f0f0;
		display: flex;
		justify-content: space-between;
		font-size: 12px;
		color: #999;
	}

	.order-info .uni-icon,
	.order-meta .uni-icon {
		margin-right: 4px;
		vertical-align: middle;
	}

	.status-rejected {
		background-color: #f56c6c;
		/* 红色背景示例 */
		color: #fff;
	}
	
</style>